<template>
  <div>
    <!-- 操作框 -->
    <div class="tableSearch">
      <el-button type="primary" @click="goBack()" size="mini">返回</el-button>
      <el-button
        type="primary"
        v-show="sureNum"
        v-if="setRole('销售确认')"
        @click="confirmInvoice()"
        size="mini"
      >销售确认</el-button>
      <el-button
        v-show="closeOrderBtn"
        v-if="setRole('关闭单据')"
        type="primary"
        @click="handleDocument(4)"
        size="mini"
      >关闭单据</el-button>
      <el-button
        v-show="cancelBtn"
        type="primary"
        v-if="setRole('取消单据')"
        @click="handleDocument(3)"
        size="mini"
      >取消单据</el-button>
      <el-button
        v-show="toexamine"
        type="primary"
        v-if="setRole('审核')"
        @click="handleDocument(5)"
        size="mini"
      >审核通过</el-button>
      <el-button
        v-show="toexamine"
        type="primary"
        v-if="setRole('审核')"
        @click="handleDocument(6)"
        size="mini"
      >审核驳回</el-button>
      <!-- 应收应付原型改变6/24删除确认按钮 -->
      <el-button type="primary" v-show="saveBtn" @click="submitSaleOrder()" size="mini">保存</el-button>
    </div>
    <!-- 表单 -->
    <el-form :model="formdata" ref="formdata" label-width="120px" size="mini">
      <el-row>
        <el-col :span="8">
          <el-form-item label="客户：">
            <el-input v-model="formdata.shopName" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <!-- 应收应付原型改变6/24 -->
          <el-form-item label="订单状态：">
            <el-input v-model="orderSaleStatusArr[formdata.statusFlow]" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="交货日期：">
            <el-date-picker
              v-model="formdata.deliveryDate"
              format="yyyy年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              type="date"
              :disabled="disabled"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单据日期：">
            <el-date-picker
              v-model="formdata.orderDate"
              format="yyyy年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              type="date"
              :disabled="disabled"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="单据号：">
            <el-input v-model="formdata.saleCode" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="来源单号：">
            <el-input v-model="formdata.purchaseCode" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 物料表格 -->
    <div class="tableMain">
      <el-table :data="tableData" stripe style="width: 100%">
        <el-table-column type="index" label="#" width="25"></el-table-column>
        <el-table-column prop="goodsCode" label="商品货号" align="center"></el-table-column>
        <el-table-column prop="barCode" label="商品条码" align="center"></el-table-column>
        <el-table-column prop="goodsName" label="商品" align="center" width="200"></el-table-column>

        <!-- 订单修改8.22 -->
        <el-table-column label="生产日期" align="center" width="200" v-if="!hasConfirmCai" key="1">
          <template slot-scope="scope">
            <el-select
              clearable
              v-if="scope.row.isBatch === '1'"
              :disabled="isConfirm"
              @change="dateInProducedChange"
              @focus="batchSelect(scope.row, scope.$index)"
              @clear="batchSelects(scope.row, scope.$index)"
              v-model="scope.row.dateInProduced"
              size="mini"
            >
              <el-option
                v-for="item in scope.row.dateAndBatch"
                :key="item.index"
                :value="item"
                :label="item"
              ></el-option>
            </el-select>
            <span v-if="scope.row.isBatch === '0'">{{"---"}}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="!hasConfirmCai" label="商品批次" align="center" width="200" key="2">
          <template slot-scope="scope">
            <el-select
              clearable
              v-if="scope.row.isBatch === '1'"
              :disabled="isConfirm"
              @change="goodsBatchNumberChange"
              @focus="batchSelect(scope.row, scope.$index)"
              @clear="batchSelects(scope.row, scope.$index)"
              v-model="scope.row.goodsBatchNumber"
              size="mini"
            >
              <el-option
                v-for="item in scope.row.batchAndDate"
                :key="item.index"
                :value="item.goodsBatchNumber"
                :label="item.goodsBatchNumber"
              ></el-option>
            </el-select>
            <span v-if="scope.row.isBatch === '0'">{{"---"}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="goodsSpec" label="规格型号" align="center" width="120px">
          <template slot-scope="scope">
            <div v-for="(item,index) in scope.row.goodsSpec" :key="index">
              <span v-if="item!=null">{{item.paramName}} :</span>
              <span v-if="item!=null">{{item.paramValue}}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="unitName" label="单位" align="center"></el-table-column>
        <el-table-column prop="purchaseNum" label="数量" align="center"></el-table-column>
        <el-table-column prop="price" label="单价" align="center"></el-table-column>
        <el-table-column prop="goodsAmount" label="总价" align="center" v-if="!hasConfirmCais">
          <template slot-scope="scope">
            <span>{{(Number(scope.row.goodsPrice)*Number(scope.row.purchaseNum)).toFixed(2)}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="goodsPrice"
          label="销售价"
          width="150"
          align="center"
          v-if="!hasConfirmCai"
        >
          <template slot-scope="scope">
            <!-- <el-input
              :disabled="isConfirm"
              v-model="scope.row.goodsPrice"
              size="mini"
              oninput="this.value=this.value.replace(/\D/g,'')"
              onafterpaste="this.value=this.value.replace(/\D/g,'')"
            ></el-input>-->
            <sd-input :val.sync="scope.row.goodsPrice" :disableds="isConfirm"></sd-input>
          </template>
        </el-table-column>
        <el-table-column
          prop="confirmNum"
          label="确认数量"
          width="150"
          align="center"
          v-if="!hasConfirmCai"
        >
          <template slot-scope="scope">
            <input
              type="text"
              style="width:100px"
              class="commonInput"
              :disabled="isConfirm"
              v-model="scope.row.confirmNum"
              size="mini"
              maxlength="8"
              oninput="this.value=this.value.replace(/\D/g,'')"
              onafterpaste="this.value=this.value.replace(/\D/g,'')"
            />
            <!-- <el-input 
              :disabled="isConfirm"
              v-model="scope.row.confirmNum"
              size="mini"
              maxlength="8"
              oninput="this.value=this.value.replace(/\D/g,'')"
            onafterpaste="this.value=this.value.replace(/\D/g,'')"></el-input>-->
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center" v-if="!hasConfirmCai">
          <template slot-scope="scope">
            <el-button
              size="small"
              @click="addSaleorder(scope.$index,scope.row)"
              type="text"
              :disabled="isConfirm"
              class="addDetail"
            >添加</el-button>
            <el-button
              size="small"
              @click="handleCancel(scope.$index,scope.row.goodsId)"
              type="text"
              :disabled="isConfirm"
              class="addDetail"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 价钱计算 -->
    <el-form label-width="120px" size="mini" style="margin-top:50px;">
      <el-row>
        <el-col :span="5">&nbsp;</el-col>
        <el-col :span="6">
          <el-form-item label="操作员：">
            <el-input v-model="formdata.creator" disabled></el-input>
          </el-form-item>
          <el-form-item label="备注：">
            <el-input v-model="formdata.remark" type="textarea" maxlength="50" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品总计：" prop="priceTotal">
            <el-input v-model="formdata.saleAmount" disabled></el-input>
          </el-form-item>
          <el-form-item label="运费：" prop="freight">
            <el-input v-model="formdata.freight" type="text" disabled></el-input>
          </el-form-item>
          <el-form-item label="应收总计：">
            <el-input v-model="formdata.amount" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="!hasConfirmCai">
          <el-form-item label="确认商品总计：" prop="priceTotal">
            <el-input v-model="confirmSaleAmount" disabled></el-input>
          </el-form-item>
          <el-form-item label="确认运费：" prop="confirmFreight">
            <sd-input :val.sync="formdata.confirmFreight" :disableds="isConfirm"></sd-input>
          </el-form-item>
          <el-form-item label="确认应收总计：">
            <el-input v-model="confirmformdataAllTotal" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="1">&nbsp;</el-col>
      </el-row>
    </el-form>
  </div>
</template>
<script>
import utils from "@/util/state";
import util from "@/util";
import { mapState } from "vuex";
import goodsList from "@/components/GoodsList";
import {
  updateGoodsSale,
  selectGoodsSaleDetails,
  getDateInProduced,
  getGoodsBatchNumber
} from "@/api";
import sdInput from "@/components/SdInput";
import { debuglog } from "util";
export default {
  components: { goodsList, sdInput },
  data() {
    return {
      sureNum: false, //确认数量按钮显示
      closeOrderBtn: false, //关闭单据按钮
      cancelBtn: false, //取消单据按钮
      editOrder: false, //修改按钮
      saveBtn: false, //保存按钮
      savaType: 0, //保存类型 1.确认数量 2.修改 3.收款确认 4.关闭订单 5.取消订单
      disabled: true,
      data: "",
      id: "",
      tableData: [], // 选择的物料数组
      orderSaleStatusArr: utils.orderSaleStatusArr, //订单状态
      formdata: {
        purchaseCode: "",
        deliveryDate: "", // 交货日期
        statusFlow: "", // 订单状态
        orderDate: "", // 单据日期
        shopName: "", //商户名称
        shopId: "", // 客户id
        goodsList: [], // 物料
        creator: "", // 操作人
        remark: "", // 备注
        goodsPrice: "",
        // purchaseAmount: 0, // 总计
        freight: 0, // 运费
        taxAmount: 0, // 税
        amount: 0, // 实收总计
        confirmSaleAmount: 0,
        confirmFreight: 0,
        confirmTax: 0,
        confirmAmount: 0,
        saleType: ""
      },
      formdataAllTotal: "",
      hasConfirmCai: true, // 是否是采购报货
      hasConfirmCais: false, //是否进行过报货确认总价
      isConfirm: true, // 是否进行过报货确认
      toexamine: false, //确认数量后的审核
      batchSelectGood: "", // 商品批次多选时定位选择的商品
      batchIndex: "", // 商品批次多选时定位位置
      warehouseId: "", //每条数据仓库id
      goodsId: "", //每条数据商品id
      userName: "",
      statusFlows: "",
      amounts: "",
      users: ""
    };
  },
  computed: {
    ...mapState({
      power: state => state.power,
      merchantId: state => state.merchantId,
      userId: state => state.userId,
      mobile: state => state.mobile,
      linkName: state => state.linkName
    }),
    confirmSaleAmount: function() {
      let totalPrice = 0;
      this.freightNum = 0.0;
      this.tableData.forEach(i => {
        totalPrice += i.goodsPrice * i.confirmNum;
        if (i.freight == undefined) {
          i.freight = 0;
        }
        this.freightNum += i.freight * i.confirmNum;
      });
      this.formdata.confirmFreight = isNaN(this.freightNum)
        ? 0
        : this.freightNum.toFixed(2);
      this.formdata.confirmSaleAmount = totalPrice.toFixed(2);
      return isNaN(totalPrice) ? 0 : totalPrice.toFixed(2);
    },
    confirmformdataAllTotal: function() {
      let totalPrice = 0;
      totalPrice =
        Number(this.confirmSaleAmount) + Number(this.formdata.confirmFreight);
      if (totalPrice == NaN || totalPrice == 0) {
        this.formdata.confirmAmount = 0;
        return totalPrice;
      } else {
        this.formdata.confirmAmount = totalPrice.toFixed(2);
        return totalPrice.toFixed(2);
      }
    }
  },
  mounted() {
    this.id = util.getQuery("id");
    this.getDataById(this.id); // 查看该订单详情
    this.init();
  },
  methods: {
    init() {
      if (this.linkName == undefined || this.linkName == "") {
        this.users = this.mobile;
      } else {
        this.users = this.linkName;
      }
    },
    // 分配权限
    setRole(key) {
      return util.selectTitle(this.power, key);
    },
    /**
     * 点击报货确认，报货确认按钮为不可点击状态，确认数量等输入框为可编辑状态
     */

    confirmInvoice() {
      this.tableData.forEach(ele => {
        if (this.statusFlows == "11") {
          ele.confirmNum = ele.confirmNum;
        } else {
          ele.confirmNum = ele.purchaseNum;
        }
        // this.$set(ele, "price", ele.goodsPrice);
      });
      this.formdata.confirmTax = this.formdata.taxAmount;
      this.hasConfirmCai = false;
      this.hasConfirmCais = true;
      this.isConfirm = false;
      this.saveBtn = true;
      this.cancelBtn = !this.cancelBtn; //取消单据按钮
      this.editOrder = !this.editOrder;
      this.sureNum = !this.sureNum;
      this.savaType = 1;
      let freight = this.formdata.freight;
      this.$nextTick(() => {
        this.formdata.confirmFreight = freight;
      });
    },
    submitSaleOrder() {
      if (this.savaType == 1) {
        this.formdata.statusFlow = 9; //确认数量后审核
      } else if (this.savaType == 2) {
        this.formdata.statusFlow = 1;
      } else if (this.savaType == 0) {
        this.formdata.statusFlow = 1;
      } else if (this.savaType == 3) {
        this.formdata.statusFlow = 2;
      } else if (this.savaType == 4) {
        this.formdata.statusFlow = 4;
      } else if (this.savaType == 5) {
        this.formdata.statusFlow = 1;
      } else if (this.savaType == 6) {
        this.formdata.statusFlow = 11;
      }
      let data = this.formdata;
      data.id = this.id;
      data.creator = this.userId;
      data.goodsList = JSON.stringify(this.tableData);
      data.amount = "";
      data.purchaseAmount = "";
      let a = true;
      let b = true;
      let c = true;
      this.tableData.forEach(item => {
        if (item.isBatch == "1") {
          if (item.goodsBatchNumber == "" || item.dateInProduced == "") {
            a = false;
            return;
          }
        }
        if (item.goodsPrice === "") {
          b = false;
          return;
        }
        if (item.confirmNum === "") {
          c = false;
          return;
        }
      });
      if (a == false && this.savaType == 1) {
        this.$message({
          type: "error",
          message: "请检查必填项商品批次，生产日期"
        });
        this.formdata.creator = "";
        this.formdata.statusFlow = this.statusFlows;
        this.formdata.amount = this.amounts;
      } else if (b == false && this.savaType == 1) {
        this.$message({
          type: "error",
          message: "销售价不能为空"
        });
        this.formdata.creator = "";
        this.formdata.statusFlow = this.statusFlows;
        this.formdata.amount = this.amounts;
      } else if (c == false && this.savaType == 1) {
        this.$message({
          type: "error",
          message: "确认数量不能为空"
        });
        this.formdata.creator = "";
        this.formdata.statusFlow = this.statusFlows;
        this.formdata.amount = this.amounts;
      } else {
        updateGoodsSale(data).then(res => {
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: res.msg
            });
            this.goBack();
          } else {
            this.formdata.creator = "";
            this.formdata.statusFlow = this.statusFlows;
            this.formdata.amount = this.amounts;
          }
        });
      }
    },
    handleDocument(type) {
      this.savaType = type;
      this.submitSaleOrder();
    },
    // 生单
    healthOrder() {
      utils.routerTo(this, "invoiceAdd", {
        saleOrderId: this.id
      });
    },
    // 点击返回按钮
    goBack() {
      util.routerTo("/order-center/sale-management/sale-salesorder");
    },
    getdatetime(now, l = "-", m = ":") {
      now = new Date(now);
      let year = now.getFullYear();
      let month = now.getMonth() + 1;
      let date = now.getDate();
      let hour = now.getHours();
      let minute = now.getMinutes();
      if (month < 10) {
        month = "0" + month;
      }
      if (date < 10) {
        date = "0" + date;
      }
      if (hour < 10) {
        hour = "0" + hour;
      }
      if (minute < 10) {
        minute = "0" + minute;
      }
      return year + l + month + l + date;
    },
    // 查看时根据id获取详情
    getDataById(goodsSaleId) {
      let data = {
        id: goodsSaleId
      };
      selectGoodsSaleDetails(data).then(res => {
        if (res.code == 200 && res.data != null) {
          this.formdata = res.data;
          this.tableData = res.data.goodsList;

          let c;
          c = {
            goodsBatchNumber: "无批次"
          };
          this.tableData.forEach(item => {
            if (item.batchAndDate == undefined) {
              item.batchAndDate = [];
              item.batchAndDate.push(c);
              item.batchAndDates=item.batchAndDate
            }else{
              item.batchAndDates=item.batchAndDate
            }
            if (item.dateAndBatch == undefined) {
              item.dateAndBatch = [];
              item.dateAndBatch[0] = "无生产日期";
              item.dateAndBatchs=item.dateAndBatch
            }else{
              item.dateAndBatchs=item.dateAndBatch
            }

          });
          this.tableData = JSON.parse(JSON.stringify(this.tableData));
          this.formdata.orderDate = this.getdatetime(res.data.orderDate);
          this.formdata.deliveryDate = this.getdatetime(res.data.deliveryDate);
          this.formdata.purchaseCode = res.data.purchaseCode;
          this.formdata.creator = res.data.userName;
          this.userName = res.data.userName;
          this.statusFlows = this.formdata.statusFlow;
          this.amounts = res.data.amount;
          this.savaType = res.data.saleType;
          if (this.formdata.statusFlow == 0) {
            //待确认状态
            this.sureNum = true;
            this.cancelBtn = true;
            this.closeOrderBtn = false;
            this.toexamine = false;
          } else if (this.formdata.statusFlow == 1) {
            //代收款状态
            this.closeOrderBtn = true;
            this.sureNum = false;
            this.cancelBtn = false;
            this.hasConfirmCai = false;
            this.hasConfirmCais = true;
            this.toexamine = false;
          } else if (this.formdata.statusFlow == 9) {
            //审核状态
            this.toexamine = true;
            this.closeOrderBtn = false;
            this.sureNum = false;
            this.cancelBtn = false;
            this.hasConfirmCai = false;
            this.hasConfirmCais = true;
          } else if (this.formdata.statusFlow == 11) {
            //审核驳回状态
            this.sureNum = true;
            this.cancelBtn = true;
            this.closeOrderBtn = false;
            this.toexamine = false;
            this.hasConfirmCai = false;
            this.hasConfirmCais = true;
          } else {
            this.closeOrderBtn = false;
            this.sureNum = false;
            this.cancelBtn = false;
            this.hasConfirmCai = false;
            this.toexamine = false;
            this.hasConfirmCais = true;
          }
          let freight = res.data.confirmFreight;
          this.$nextTick(() => {
            this.formdata.confirmFreight = freight;
          });
        }
      });
    },
    // 订单修改8.22
    // 商品批次
    goodsBatchNumberChange(val) {
      if (val) {
        this.getDateInProducedlist(val);
      }
    },
    // 生产日期接口
    getDateInProducedlist(val) {
      getDateInProduced({
        goodsId: this.goodsId,
        repositoryId: this.warehouseId,
        goodsBatchNumber: val
      }).then(res => {
        if (res.data.list.length == "0") {
          res.data.list[0] = "无生产日期";
        }
        let i = this.batchIndex;
        this.$delete(this.tableData[i], "dateAndBatch");
        this.$set(this.batchSelectGood, "dateAndBatch", res.data.list);
        this.tableData[i] = this.batchSelectGood;
        if (res.data.list.length == "1") {
          res.data.list.forEach(item => {
            this.tableData[i].dateInProduced = item;
          });
        }
      });
    },
    // 商品批次接口
    getGoodsBatchNumberlist(val) {
      getGoodsBatchNumber({
        goodsId: this.goodsId,
        repositoryId: this.warehouseId,
        dateInProduced: val
      }).then(res => {
        let a;
        a = {
          goodsBatchNumber: "无批次"
        };
        if (res.data.list.length == "0") {
          res.data.list.push(a);
        }
        let i = this.batchIndex;
        this.$delete(this.tableData[i], "batchAndDate");
        this.$set(this.batchSelectGood, "batchAndDate", res.data.list);
        this.tableData[i] = this.batchSelectGood;
        if (res.data.list.length == "1") {
          res.data.list.forEach(item => {
            this.tableData[i].goodsBatchNumber = item.goodsBatchNumber;
          });
        } else {
          this.$set(this.batchSelectGood, "batchAndDate", res.data.list);
          res.data.list.forEach(item => {
            this.tableData[i].goodsBatchNumber = "";
          });
        }
      });
    },
    // 选中每一行数据时
    batchSelect(good, index) {
      this.batchSelectGood = good;
      this.goodsId = this.batchSelectGood.goodsId;
      this.warehouseId = this.batchSelectGood.warehouse;
      this.batchIndex = index;
    },
    batchSelects(good, index, val) {
      this.batchSelectGood = good;
      this.goodsId = this.batchSelectGood.goodsId;
      this.warehouseId = this.batchSelectGood.warehouse;
      this.batchIndex = index;
      this.batchSelectGood.dateInProduced = "";
      this.batchSelectGood.goodsBatchNumber = "";
      val = "";
      this.getDateInProducedlist(val);
      this.getGoodsBatchNumberlist(val);
    },
    // 生产日期
    dateInProducedChange(val) {
      if (val) {
        this.getGoodsBatchNumberlist(val);
      }
    },
    // 操作添加
    addSaleorder(index, rows) {
      this.tableData.splice(index++, 0, rows);
      this.tableData = this.tableData.map(item => {
        //遍历每次创建商品
        return {
          goodsBatchNumber: item.goodsBatchNumber,
          dateInProduced: item.dateInProduced,
          dateAndBatch: item.dateAndBatchs,
          dateAndBatchs: item.dateAndBatchs,
          batchAndDate: item.batchAndDates,
          batchAndDates: item.batchAndDates,
          goodsName: item.goodsName,
          barCode: item.barCode,
          confirmNum: item.confirmNum,
          createTime: item.createTime,
          freight: item.freight,
          goodsAmount: item.goodsAmount,
          goodsCode: item.goodsCode,
          goodsId: item.goodsId,
          goodsPrice: item.goodsPrice,
          price: item.price,
          goodsSpec: item.goodsSpec,
          goodsUnit: item.goodsUnit,
          id: item.id,
          isBatch: item.isBatch,
          purchaseDetailId: item.purchaseDetailId,
          purchaseNum: item.purchaseNum,
          saleCode: item.saleCode,
          saleId: item.saleId,
          sendNum: item.sendNum,
          status: item.status,
          display: item.display,
          unitName: item.unitName
        };
      });
      this.tableData[index].goodsBatchNumber = "";
      this.tableData[index].dateInProduced = "";
    },
    //  删除商品
    handleCancel(index,id) {
      let ary = [];
      // let a = false;
      this.tableData.forEach((x, index) => {
        ary.push(x.goodsId);
      });
      // for (var i = 0; i < ary.length; i++) {
      //   if (ary[i] == ary[i + 1]) {
      //     a = true;
      //     // return;
      //   }
      // }
      let num=0
      for (var i = 0; i < ary.length; i++) {
        if (ary[i] == id) {
         num = num + 1;
        }
      }
      if (num != "1") {
        this.tableData.splice(index, 1);
      } else {
        this.$message({
          type: "error",
          message: "订单需要留一条数据"
        });
      }
    }
  }
};
</script>

